package com.chen.service.impl;

import com.chen.dao.BaseDAO;
import com.chen.pojo.Visit;
import com.chen.pojo.PageBean;
import com.chen.service.VisitService;
import com.chen.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * com.chen.service.impl
 * 作者      : 陈晓
 * 描述      :
 * 创建日期  : 2018/4/29
 * 修改日期  :
 */
@Service("/visitService")
@Transactional
public class VisitServiceImpl implements VisitService {

  @Autowired
  private BaseDAO<Visit> baseDAO;

  private static List<Object> list;

  public void insert(Visit visit)throws Exception {
    baseDAO.save(visit);
  }

  public List<Visit> getList(Visit visit, PageBean pageBean)throws Exception {
    StringBuilder sb = new StringBuilder("select v from Visit as v ");
    list = new ArrayList<Object>();
    String sql = getSql(visit, sb);
    String hql = sql + " order by v.id desc ";
    return baseDAO.find(hql.replaceFirst("and", "where"), list, pageBean);
  }

  public long getCount(Visit visit)throws Exception {
    StringBuilder sb = new StringBuilder("select count(v) from Visit as v ");
    list = new ArrayList<Object>();
    String sql = getSql(visit, sb);
    if (list.size() > 0)
      return baseDAO.count(sql.replaceFirst("and", "where"),list);
    return baseDAO.count(sql.replaceFirst("and", "where"));
  }

  @Override
  public void update(Visit visit) throws Exception {
     baseDAO.update(visit);
  }

  /**
   * 获得执行语句Sql
   *
   * @param visit 对象
   * @param sb       sql语句
   * @return 返回sql语句
   */
  private String getSql(Visit visit, StringBuilder sb) {
    if (visit != null) {
      if (StringUtil.isNotEmpty(visit.getCustomername())) {
        sb.append(" and v.customername like ? ");
        list.add("%"+visit.getCustomername()+"%");
      }
      if (StringUtil.isNotEmpty(visit.getReceptionpeople())) {
        sb.append(" and v.receptionpeople like ? ");
        list.add("%"+visit.getReceptionpeople()+"%");
      }
      if (StringUtil.isNotEmpty(visit.getReceptiondepartment())) {
        sb.append(" and v.receptiondepartment like ? ");
        list.add("%"+visit.getReceptiondepartment()+"%");
      }
      if (StringUtil.isNotEmpty(visit.getDoorpostname())) {
        sb.append(" and v.doorpostname like ? ");
        list.add("%"+visit.getDoorpostname()+"%");
      }
    }
    return sb.toString();
  }

  /**
   * 获得参数值
   *
   * @param list 参数值列表
   * @return 参数值
   */
  private Object[] getParams(List<String> list) {
    Object[] params = new Object[list.size()];
    for (int i = 0; i < list.size(); i++) {
      params[i] = list.get(i);
    }
    return params;
  }
}
